<?php
namespace app\faxing\channel;


use app\common\model\Gameulog;
use app\common\model\Order;
use app\common\model\Player;
use app\common\model\PlayerRole;
use app\index\controller\Exception;
use think\cache\driver\Redis;
use think\Db;
use think\facade\Log;
use think\facade\Session;
use app\common\controller\FaXingBase;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Qiqisy extends FaXingBase
{

    public function register($params)
    {
        $cid = $params['cid'];
        $sign_data = $params;
        unset($sign_data['cid']);
        unset($sign_data['gid']);
        $sign = $sign_data['sign'];
        unset($sign_data['sign']);
        $check_sign = $this->createSign($sign_data,$this->extdata['Appkey']);

        if($check_sign != $sign){
            $this->error("签名错误");
        }

        $account = $cid."_".$params['uid'];
        $player = Player::getOne(['account'=>$account]);
        if(!$player){
            //注册
            $data['account'] = $account;
            $data['password'] = get_encrypt('123456');
            $data['type'] = 0;
            $data['cid'] = $this->cid;
            $data['gid'] = $this->gid;
            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error("登录失败，请稍后再试。");
                Log::info("用户注册失败:".$e->getMessage());
            }
        }
        $game = $this->game;
        $data['uid'] = $player['id'];
        //记录登录信息
        Gameulog::addLog($data);
        $token = get_encrypt($data['uid']);
        $player['token'] = $token;
        unset($player['password']);
        $player['third_data'] = $params;
        Session::set('palyerinfo', json_encode($player));
        //redis 保存用户信息
        $redis = new Redis();
        $redis->set($token, $player);
        if (strpos($game['api_login_url'], '?') !== false) {
            $game_url = $game['api_login_url']."&token=".$token;
        } else {
            $game_url = $game['api_login_url']."?token=".$token;
        }
        return ['game_url'=>$game_url,'token'=>$token];
    }

    public function order($order)
    {
        $account = get_player($order['uid'],'account');
        $sign = get_sign(['order_no'=>$order['order_no']],$this->extdata['Appkey']);

        $data = [
            'amount' => (int) $order['amount'],//金额 整数：元
            'product_id' => rand(000000,999999),//商品id
            'product_name' => $order['goods_name'],//商品名称
            'game_uid' => $account,//游戏方用户id
            'game_orderno' => $order['order_no'],//游戏方生成的订单号
            'ext' => $sign,
        ];
        $data['sign'] = $this->createSign($data,$this->extdata['Appkey']);
        return $data;
    }

    public function check_order($params)
    {
        if(!empty($params['game_orderno'])){
            echo json_encode(['status'=>3,'message'=>'订单号错误']);exit;
        }
        $order_no = $params['game_orderno'];
        $sign = $params['ext'];

        // 双重校验
        $order_sign = get_sign(['order_no'=>$order_no],$this->extdata['Appkey']);

        if($order_sign != $sign){
            echo json_encode(['status'=>3,'message'=>'签名错误']);exit;
        }

        if(!$this->check_sign($params,$this->extdata['Appkey'])){
            echo json_encode(['status'=>'fail']);exit;
        }

        if(!$this->query_order($order_no,$params['orderno'])){
            echo json_encode(['status'=>'fail']);exit;
        }
        // 查询订单
        $order = Order::where([
            'order_no'=>$order_no
        ])->find();

        if($order['amount'] != $params['money']){
            echo json_encode(['status'=>'fail']);exit;
        }
        $order->trade_no = $params['orderno'];
        $order->save();

        return $order;
    }

    public function message($message,$order)
    {
        echo $message === 'success' ? json_encode(['status'=>'success']) :  json_encode(['status'=>'fail']);
        exit;
    }

    public function create_role($params)
    {
        $redis = new Redis();
        $player = $redis->get($params['token']);
        $third_data = $player['third_data'];

        $url = "https://api.77sy.com.cn/sdk/gameRoleReport?token=".$third_data['token'];

        $data = [
            'game_uid' => $player['account'],
            'server_id' => (int) $params['sid'],
            'server_name' =>$params['sid'],
            'role_id' => $params['role_id'],
            'role_name' => $params['role_name'],
            'role_level' => $params['role_level'],
            'role_revival' => 0,
            'role_power' => $params['role_power'],
            'vip' => 0,
            'ext' => "",
        ];
        $data['sign'] = $this->createSign($data,$this->extdata['Appkey']);
        $res = curlRequest($url,$data);
        echo $res['data'];exit;
    }

    /**
     * 订单确认
     * @param $game_order_no
     * @param $order_no
     * @return bool
     * @throws \Exception\
     */
    private function query_order($game_order_no,$order_no){
        $url = "https://api.77sy.com.cn/sdk/payQuery";
        $data = [
            'orderno'=>$order_no,
            'game_orderno' => $game_order_no
        ];
        $data['sign'] = $this->createSign($data,$this->extdata['Appkey']);
        $res = curlRequest($url,$data,[],"POST",'form');
        if(!empty($res['data'])){
            return false;
        }
        $result = json_decode($res['data'],true);

        if(!empty($result) && $result['code'] == 0){
            return false;
        }
        // 校验
        $return_data = $result['data'];
        $sign = $return_data['sign'];
        unset($return_data['sign']);
        $check_sign = $this->createSign($return_data);
        if($check_sign != $sign){
            return false;
        }
        if($return_data['pay_state'] == 0){
            return false;
        }
        return true;
    }

    private function createSign($params, $key) {
        //按照参数名 ASCII 码从小到大排序
        ksort($params);
        //使用#拼接 value 值和 gameSecret 值
        $str = implode('#', $params) . '#' . $key;
        //进行 base64 编码
        $base64 = base64_encode($str);
        //进行 md5 编码，32小写
        $md5Str = md5($base64);

        return md5($md5Str);
    }

    protected function check_sign($params, $key)
    {
        $sign_data = $params;
        unset($sign_data['cid']);
        unset($sign_data['gid']);
        $sign = $sign_data['sign'];
        unset($sign_data['sign']);

        $check_sign = $this->createSign($sign_data,$key);

        if($check_sign != $sign){
            return false;
        }
        return true;
    }

}